package com.topisv.tms.rest.qimen.qmcontroller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXB;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.topisv.tms.entity.qimen.DeliveryOrderTask;
import com.topisv.tms.exception.ErrorCode;
import com.topisv.tms.exception.PaiUException;
import com.topisv.tms.exception.QMErrorCode;
import com.topisv.tms.rest.qimen.command.IQMRequestCommand;
import com.topisv.tms.rest.qimen.command.QMRequestCommandContainer;
import com.topisv.tms.rest.qimen.qmentity.response.QMReponse;
import com.topisv.tms.rest.qimen.qmentity.response.ResponseFlagType;
import com.topisv.tms.rest.qimen.request.RequestParams;
import com.topisv.tms.rest.qimen.request.parse.RequestParamsParse;
import com.topisv.tms.rest.qimen.response.ResponseParams;
import com.topisv.tms.service.qimen.DeliveryOrderTaskService;
import com.topisv.tms.utils.TopUtils;
import com.topisv.tms.web.base.BaseController;

/**
 *  奇门API接口
 *  Date          Author       Version       Description
 * ----------------------------------------------------------
 *  2015-4-28      CC            1.0           Create
 */
@Controller
@RequestMapping(value = "/api/tt/wms")
public class QiMenController extends BaseController {
	
	@RequestMapping(value = "service", method = RequestMethod.POST)
	public void service(final HttpServletRequest request, final HttpServletResponse response) {
		IQMRequestCommand requestCommand = null;
		try {
			RequestParams requestParam = RequestParamsParse.parseRequestParam(request);
			// 1：校验请求
			log.info("--------qimen request beigin");
//			check(requestParam);
			// 2：分发请求
			String method = requestParam.getParams().get(RequestParamsParse.METHOD);
			log.info("request method {}",method);
			requestCommand = QMRequestCommandContainer.getInstance().get(method);
			log.info("-----奇门接收报文 {}",requestParam.getRequestXml());
			ResponseParams qmResponse = requestCommand.execute(requestParam);
			// 3:返回结果
			IOUtils.write(qmResponse.getResponseXml().getBytes("UTF-8"), response.getOutputStream());
			log.info("-----响应完成:{}",qmResponse.getResponseXml());
			
		} catch (PaiUException e) {
			log.error("QiMenController case some error", e);
			QMReponse qmResponse = new QMReponse();
			qmResponse.setFlag(ResponseFlagType.FAILURE.getType());
			qmResponse.setCode(e.getErrorCode());
			qmResponse.setMessage(e.getMessage());
			try {
				JAXB.marshal(qmResponse, response.getOutputStream());
			} catch (IOException e1) {
				log.error("write to qimen error.",e1);
			}
		} catch (Exception e) {
			log.error("QiMenController case some error", e);
			QMReponse qmResponse = new QMReponse();
			qmResponse.setFlag(ResponseFlagType.FAILURE.getType());
			qmResponse.setCode(ErrorCode.DATA_ERROR.getCode());
			qmResponse.setMessage(ErrorCode.DATA_ERROR.getMessage());
			try {
				JAXB.marshal(qmResponse, response.getOutputStream());
			} catch (IOException e1) {
				log.error("write to qimen error.",e1);
			}
		}
		log.info("--------qimen request end ");
	}
	
	@ResponseBody
	@RequestMapping(value = "useDistributeWarehouse", method = RequestMethod.POST)
    public String useDistributeWarehouse(String type) {
	    if ("open".equals(type)) {
	        DeliveryOrderTaskService.useDistributeWarehouse = true;
	        return "Distribute Warehouse Open";
        }else if ("close".equals(type)) {
            DeliveryOrderTaskService.useDistributeWarehouse = false;
            return "Distribute Warehouse Close";
        }
        return "param not allow";
	}
	
	private void check(RequestParams requestParam) throws Exception {
		String sign = TopUtils.signQMRequest(requestParam);
		if (!sign.equals(requestParam.getSign())) {
			log.info("org sign {} my sign {}", requestParam.getSign(), sign);
			throw new PaiUException(QMErrorCode.SIGN_CHECK_ERROR);
		}
	}

}
